﻿using System;
using System.Collections;
using System.Collections.Concurrent;
using System.Configuration;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using EKAABSInformationManagement.Database;
using EKAABSInformationManagement.Service;

namespace EKAABSInformationManagement.ConsoleApp
{
    class Program
    {
        public static CancellationTokenSource cts;
        public static NetworkService nw_service = new NetworkService();
        public static string uesrName = ConfigurationManager.AppSettings["userName"];
        public static string pwd = ConfigurationManager.AppSettings["password"];
        public static string serviceUri = ConfigurationManager.AppSettings["serviceUri"];
        static void Main(string[] args)
        {
            int maxDegreeOfParallelism = default(int);
            Int32.TryParse(ConfigurationManager.AppSettings["MaxDegreeOfParallelism"], out maxDegreeOfParallelism);
            if (maxDegreeOfParallelism == 0) maxDegreeOfParallelism = 10;
            cts = new CancellationTokenSource();
            ParallelOptions pOption = new ParallelOptions() { CancellationToken = cts.Token };
            pOption.MaxDegreeOfParallelism = maxDegreeOfParallelism;
            Task tasks = new Task(() =>
            {
                Task.Factory.StartNew(() => preOverDue_Network());
                Task.Factory.StartNew(() => overDued_Network());
            }, cts.Token);
            tasks.Start();
            System.Console.WriteLine("线程开始执行...！");
            tasks.Wait();
            System.Console.WriteLine("线程执行完毕！");
            Console.ReadLine();
        }

        private static void preOverDue_Network()
        {
            try
            {
                DateTime overDueDate = getDateByCustomerConfig(DateTime.Now, ConfigurationManager.AppSettings["fixedOverDue"], ConfigurationManager.AppSettings["fixedOverDueUnit"]);
                DateTime preOverDueDate = getDateByCustomerConfig(overDueDate, ConfigurationManager.AppSettings["fixedPreOverDue"], ConfigurationManager.AppSettings["fixedPreOverDueUnit"]);
                List<network> preOverDue_nw = nw_service.getPreOverdueNWInfo_By_Fixeddate(overDueDate, preOverDueDate);
                Parallel.For(0, preOverDue_nw.Count, (i) =>
                {
                    nw_service.update_NetworkStatus_By_MAC(preOverDue_nw[i].MAC, 2);
                    networkInfo_mail mailInfo = nw_service.getNetworkInfoForMail_By_MAC(preOverDue_nw[i].MAC);
                    string mailBody = string.Concat("Hi ", mailInfo.owner, @"\r\n\r\n你的一个网络（资产ID：）", mailInfo.assetID, ",MAC:" + mailInfo.MAC, @")即将过期，请激活。\r\n\r\nRegards,\r\nPA");
                    mailService.sendMail(uesrName, pwd, serviceUri, "网络状态即将过期", mailBody, mailInfo.email, string.Empty);
                });
            }
            catch (Exception ex)
            {
                System.Console.WriteLine("Error occured on " + System.DateTime.Now.ToString() + " while procesing preOverDue_Network, error message:" + ex.Message);
            }
        }

        private static void overDued_Network()
        {
            try
            {
                DateTime overDueDate = getDateByCustomerConfig(DateTime.Now, ConfigurationManager.AppSettings["fixedOverDue"], ConfigurationManager.AppSettings["fixedOverDueUnit"]);
                List<network> OverDue_nw = nw_service.getOverduedNWInfo_By_Fixeddate(overDueDate);
                Parallel.For(0, OverDue_nw.Count, (i) =>
                {
                    nw_service.update_NetworkStatus_By_MAC(OverDue_nw[i].MAC, 3);
                    networkInfo_mail mailInfo = nw_service.getNetworkInfoForMail_By_MAC(OverDue_nw[i].MAC);
                    string mailBody = string.Concat("Hi ", mailInfo.owner, "\r\n\r\n你的一个网络（资产ID：", mailInfo.assetID, ",MAC:" + mailInfo.MAC, "）已经过期，请激活。\r\n\r\nRegards,\r\nPA");
                    mailService.sendMail(uesrName, pwd, serviceUri, "网络状态已经过期", mailBody, mailInfo.email, string.Empty);
                });
            }
            catch (Exception ex)
            {
                System.Console.WriteLine("Error occured on " + System.DateTime.Now.ToString() + " while procesing preOverDue_Network, error message:" + ex.Message);
            }
        }
        private static DateTime getDateByCustomerConfig(DateTime dt, string value, string unit)
        {
            DateTime reslut = default(DateTime);
            int val = default(int);
            Int32.TryParse(value, out val);
            if (val == 0)
            {
                System.Console.WriteLine("Value for 'fixedOverDue' is not a number!", EventLogEntryType.Error);
                cts.Cancel();
            }
            switch (unit)
            {
                case "day":
                    reslut = dt.AddDays(-val);
                    break;
                case "week":
                    reslut = dt.AddDays(-val * 7);
                    break;
                case "month":
                    reslut = dt.AddMonths(-val);
                    break;
                case "year":
                    reslut = dt.AddYears(-val);
                    break;
                default:
                    System.Console.WriteLine("Value for 'fixedOverDueUnit' is invalidated!", EventLogEntryType.Error);
                    cts.Cancel();
                    break;
            }
            return reslut;
        }
    }
}
